//
//  WebViewController.swift
//  ShowH5
//
//  Created by kuaimaxiansheng on 2022/12/7.
//

import UIKit
import WebKit

class WebViewController: BaseViewController {
    var vrWebFlag: Bool = false //vr进来的,不显示title
    var handlerMethod:[String] = ["isApp"]
    var webView: WKWebView!
    var urlStr: String = ""
    var titleStr: String = ""   //标题
    var localHtmlStr: String = ""  //本地html标签
    var webViewHeight: CGFloat = 0.01
    var bodyColorHex: String = "#F2F7FA"
    var progressView: UIProgressView! = {
        let tempProgressView = UIProgressView.init(frame: CGRect.init(x: 0, y: NavBarHight-2, width: kScreenWidth, height: 2))
        tempProgressView.backgroundColor = UIColor.white
        tempProgressView.progressTintColor = UIColor.blue
        return tempProgressView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.navBar.backgroundColor = .white
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.navBar.title = self.titleStr

        let configuretion = WKWebViewConfiguration.init()
        configuretion.preferences = WKPreferences()
        configuretion.preferences.minimumFontSize = 0
        configuretion.preferences.javaScriptEnabled = true
        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuretion.userContentController = WKUserContentController()
        for item in self.handlerMethod {
            configuretion.userContentController.add(self, name: item)
        }
        webView = WKWebView.init(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), configuration: configuretion)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.backgroundColor = UIColor.init(hex: 0xF2F7FA)
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        }
        webView.scrollView.showsHorizontalScrollIndicator = false
        self.view.addSubview(webView)
        
        
        if self.localHtmlStr == "" {
            self.localHtmlStr = " "
        }
        
        if self.urlStr != "" {
            guard let url = URL.init(string: self.urlStr) else {
                return
            }
            self.webView.load(URLRequest.init(url: url))
        }else if self.localHtmlStr != "" {
            let formatWeb = """
                    <!DOCTYPEhtml>
                        <html>
                        <head>
                            <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                            <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                        </head>
                        <style type="text/css">
                            img{
                                display:inline-block;
                                max-width:100%@;
                            }
                        </style>
                        <body style="background-color: %@">
                            %@
                        </body>
                        </html>
                    """
            let tempStr = String(format: formatWeb,
                                 "%",
                                 bodyColorHex,
                                 self.localHtmlStr)
            self.webView.scrollView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
            self.webView.loadHTMLString(tempStr, baseURL: nil)
        }
    }
    
    ///监听进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressView.progress = Float(self.webView.estimatedProgress)
        }
        if self.webView.estimatedProgress == 1 {
            self.webView.isHidden = true
        }else{
            self.webView.isHidden = false
        }
    }
    
    /////获取当前webview的title
    @objc private func toH5Token(webvView: WKWebView){
        if self.webView != nil {
            self.webView.evaluateJavaScript("document.title", completionHandler: {
                (titleStr, error) in
                if let tempTitle = titleStr as? String, tempTitle != ""  && self.vrWebFlag == false {
                    self.navBar.title = tempTitle
                }
            })
        }
    }
}

extension WebViewController: WKScriptMessageHandler, WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //ios9 延时一点才会有效
        self.perform(#selector(toH5Token(webvView:)), with: webView , afterDelay: 1)
//        webView.evaluateJavaScript("document.body.offsetHeight") { (result, error) in
//            if result == nil{
//                return
//            }
//            let documentheight = result as! CGFloat
//            webView.evaluateJavaScript("document.body.offsetWidth", completionHandler: { (result , error) in
//                let documentwidth = result as! CGFloat
//                _ = documentwidth/documentheight as CGFloat
//                self.webViewHeight = self.webView.frame.size.height
//            })
//        }
    }
    
    ///js调用ios方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.name)
        let msgBody = message.body as? String
        switch message.name {
            case "isApp":
                webView.evaluateJavaScript("isAppBack(1)") { (item, error)  in
                }
                
            default:
                ()
        }
    }
    
    ///服务器开始请求的时候调用 过滤域名
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    ///开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
}

//
//extension WebViewController: WKUIDelegate{
//
//    // 获取js 里面的提示
//    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
//
//        let alert = UIAlertController(title:  "提示", message: message, preferredStyle: .alert)
//        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) -> Void in
//            completionHandler()
//        }))
//        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) -> Void in
//            completionHandler()
//        }))
//        self.present(alert, animated: true, completion: nil)
//    }
//
//    // js 信息的交流
//    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
//
//        let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
//        alert.addAction(UIAlertAction(title:  "确定", style: .default, handler: { (_) -> Void in
//            completionHandler(true)
//        }))
//        alert.addAction(UIAlertAction(title:  "取消", style: .cancel, handler: { (_) -> Void in
//            completionHandler(false)
//        }))
//        self.present(alert, animated: true, completion: nil)
//    }
//
//    // 交互。可输入的文本。
//    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
//
//        let alert = UIAlertController(title: prompt, message: defaultText, preferredStyle: .alert)
//
//        alert.addTextField { (textField: UITextField) -> Void in
//            textField.textColor = UIColor.red
//        }
//        alert.addAction(UIAlertAction(title:  "确定", style: .default, handler: { (_) -> Void in
//            completionHandler(alert.textFields![0].text!)
//        }))
//        self.present(alert, animated: true, completion: nil)
//    }
//
//}
